<?php

namespace app\tools;

use Exception;
use GatewayClient\Gateway;
use think\Session;

/**
 * workerman服务通讯
 *
 * user ：Du
 * Date : 2022/3/23
 * Time : 14:35
 * Class Workerman
 * @package projects\tools
 */
class Workerman
{

    /**
     * 服务器地址
     *
     * User : Du
     * Date : 2022/3/23
     * Time : 14:42
     * @var string
     */
    private static string $ip = '';

    /**
     * 服务端推送消息
     *
     * User : Du
     * Date : 2022/3/23
     * Time : 14:42
     * @param array $data
     * @param string $type
     * @throws Exception
     */
    public static function sendMessage(array $data, string $type): void
    {
        Gateway::$registerAddress = env('workerman.ip') . ":" . env('workerman.port');
        switch ($type) {
            case 'all':
                Gateway::sendToAll(arrayToJson($data));
                break;
            default:
        }
    }

    /**
     * 客户端是否在线
     * @param string $clientId
     * @return int
     */
    public static function isOnline(string $clientId): int
    {
        return Gateway::isOnline($clientId);
    }

    /**
     * 客户端id绑定用户id
     *
     * User : Du
     * Date : 2022/3/23
     * Time : 17:38
     * @param array $data
     */
    public static function bingUser(array $data): void
    {
        Gateway::$registerAddress = env('workerman.ip') . ":" . env('workerman.port');
        Gateway::bindUid($data['client_id'], $data['id']);
    }

    /**
     * 获取全部客户端连接数
     * @return int
     */
    public static function getClientIdCount(): int
    {
        Gateway::$registerAddress = env('workerman.ip') . ":" . env('workerman.port');
        $count = Gateway::getAllClientIdCount();
        return $count ?? 0;
    }

    /**
     * 获取分组所在客户端连接数
     * @return int
     */
    public static function getClientIdCountByGroup(): int
    {
        $groupName = env('app.name');
        Gateway::$registerAddress = env('workerman.ip') . ":" . env('workerman.port');
        $count = Gateway::getClientIdCountByGroup($groupName);
        return $count ?? 0;
    }

    /**
     * 获取全部Uid数量
     * @return int
     */
    public static function getUidCount(): int
    {
        Gateway::$registerAddress = env('workerman.ip') . ":" . env('workerman.port');
        $count = Gateway::getAllUidCount();
        return $count ?? 0;
    }

    /**
     * 获取分组所在Uid数量
     * @return int
     */
    public static function getUidCountByGroup(): int
    {
        $groupName = env('app.name');
        Gateway::$registerAddress = env('workerman.ip') . ":" . env('workerman.port');
        return Gateway::getUidCountByGroup($groupName);
    }

    /**
     * 加入分组
     * @param string $clientId
     */
    public static function joinGroup(string $clientId): void
    {
        $groupName = env('app.name');
        Gateway::joinGroup($clientId, $groupName);
    }
}